<template>
  <div class="CPT_CODE border01 flexMode">
    <div class="lineArea flexMode flexV w80 vr border-r01">
      <span v-for="it in lines" :key="it" class="txt-dark3 p0-5 fs12">
        {{ it }}
      </span>
    </div>
    <div class="flexGrow" v-highlight>
      <pre>
        <code :class="format" class="fs12">{{code}}</code>
      </pre>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    dt: {
      type: String,
      default: "",
    },
    format: {
      type: String,
      default: "js",
    },
  },
  data() {
    return {
      code: "",
      lines: 0,
    }
  },
  created() {
    let dtArray = this.dt.split("\n"),
      lines = [],
      len = dtArray.length,
      itsHead = true,
      body = []
    //排除前空行
    for (let i = 0; i < len; i++) {
      let it = dtArray[i]
      it = it.replace(/(^\s*)|(\s*$)/g, "")
      if (it) {
        body.push(it)
        itsHead = false
      } else {
        if (!itsHead) {
          body.push(it)
        }
      }
    }
    let bodyLen = body.length
    let res = []
    //排除后空行
    for (let i = bodyLen; i >= 0; i--) {
      let it = body[i]
      if (it) {
        res.unshift(it)
        itsHead = true
      } else {
        if (itsHead) {
          res.unshift(it)
        }
      }
    }
    let resLen = res.length
    let dt = []
    //格式化空格
    for (let i = 0; i < resLen; i++) {
      let it = res[i]
      dt.push(it)
      lines.push(i + 1)
    }
    let code = dt.join("\n")
    code = this.$format(code, this.format)
    this.lines = lines
    this.code = code
  },
}
</script>
